﻿//-----------------------------------------------------------------------
// <copyright file="PublicationWireupStrategy.cs" company="iron9light">
//      Copyright (c) iron9light. All rights reserved.
// </copyright>
// <author>iron9light</author>
//-----------------------------------------------------------------------

namespace EventBrokerExtension
{
    using EventBroker;

    using Microsoft.Practices.ObjectBuilder2;

    public class PublicationWireupStrategy : EventBrokerStrategyBase
    {
        /// <summary>
        /// Called during the chain of responsibility for a build operation. The
        /// PreBuildUp method is called when the chain is being executed in the
        /// forward direction.
        /// </summary>
        /// <param name="context">Context of the build operation.</param>
        public override void PreBuildUp(IBuilderContext context)
        {
            if (context.Existing != null)
            {
                IPublicationSelectorPolicy policy = context.Policies.Get<IPublicationSelectorPolicy>(context.BuildKey);

                if (policy != null)
                {
                    IEventBroker broker = GetBroker(context);

                    foreach (PublicationInfo publicationInfo in policy.GetPublicationInfos(context))
                    {
                        broker.RegisterPublication(publicationInfo.EventTopic, context.Existing, publicationInfo.TargetEvent.Name);
                    }
                }
            }
        }

        /// <summary>
        /// Called during the chain of responsibility for a teardown operation. The
        /// PreTearDown method is called when the chain is being executed in the
        /// forward direction.
        /// </summary>
        /// <param name="context">Context of the teardown operation.</param>
        public override void PreTearDown(IBuilderContext context)
        {
            if (context.Existing != null)
            {
                IEventBroker broker = GetBroker(context);
                broker.UnregisterPublisher(context.Existing);
            }
        }
    }
}
